// Time:  O(n)
// Space: O(n)

#include <unordered_map>
#include <vector>
#include <iostream>
#include <cassert>
using namespace std;

class Solution {
public:
    int findMaxLength(vector<int>& nums) {

        int sum = 0, maxLen = 0;
        unordered_map<int, int> seen;
        seen[0] = -1;

        for(int i=0; i<nums.size(); i++) {
            sum += nums[i] == 1 ? 1 : -1;
            if(seen.count(sum)) {
                maxLen = max(maxLen, i - seen[sum]);
            } else {
                seen[sum] = i;
            }
        }
        return maxLen;
    }
};


int main() {
    Solution solution;

    // Test case 1
    vector<int> nums1 = {0, 1};
    int expected1 = 2;
    assert(solution.findMaxLength(nums1) == expected1);

    // Test case 2
    vector<int> nums2 = {0, 1, 0};
    int expected2 = 2;
    assert(solution.findMaxLength(nums2) == expected2);

    // Test case 3
    vector<int> nums3 = {0, 0, 1, 1, 0, 1};
    int expected3 = 6;
    assert(solution.findMaxLength(nums3) == expected3);

    // Test case 4
    vector<int> nums4 = {0, 1, 1, 0, 1, 1, 1, 0};
    int expected4 = 4;
    assert(solution.findMaxLength(nums4) == expected4);

    // Test case 5
    vector<int> nums5 = {1, 1, 1, 1};
    int expected5 = 0;
    assert(solution.findMaxLength(nums5) == expected5);

    cout << "All test cases passed!" << endl;

    return 0;
}